from django.db.models import Q
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework.generics import ListAPIView

from xyz.models import Article, User, Spit, Comment
from xyz.serializers.search import ArticleSearchSerializer

from django.db import transaction

from xyz.utils.page import Page


class ArticleSearchView(HaystackViewSet):
    index_models = [Article]

    serializer_class = ArticleSearchSerializer
    pagination_class = Page


class PublishCommentView(APIView):

    def post(self, request, id):
        token = request.auth
        toke_user = jwt_decode_handler(token)
        user_id = toke_user["user_id"]
        article = request.data.get('article')
        content = request.data.get('content')
        parent = request.data.get('parent')
        if parent:
            with transaction.atomic():
                save_point = transaction.savepoint()
                Comment.objects.create(
                    parent_id=parent,
                    content=content,
                    user_id=user_id,
                    article_id=id
                )
                spit_parent = Article.objects.get(id=article)
                spit_parent.comment_count += 1
                spit_parent.save()
                transaction.savepoint_commit(save_point)
        else:
            with transaction.atomic():
                save_point = transaction.savepoint()
                Comment.objects.create(
                    content=content,
                    user_id=user_id,
                    article_id=id
                )
                spit_parent = Article.objects.get(id=article)
                spit_parent.comment_count += 1
                spit_parent.save()
                transaction.savepoint_commit(save_point)
        return Response({'message': '评论成功', 'success': True})
